//
//  zhWallView.m
//  zhPopupControllerDemo
//
//  Created by zhanghao on 2016/11/3.
//  Copyright © 2017年 zhanghao. All rights reserved.
//

#import "zhWallView.h"
#import "JKSongsMessStatus.h"
#import "UIImage+Tint.h"
#import "LSZDownloadCell.h"
#import "LCHistoryDataManager.h"

////////////////////////////
// MARK -zhWallViewCell - //
////////////////////////////

static NSString *zh_CellIdentifier = @"zh_wallViewCollectionCell";
#define LISTCELL @"WallViewCell"
@interface zhWallViewCell : UITableViewCell

@property (nonatomic, assign) BOOL isPlayerVC;

@end
@interface zhWallViewCell ()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic,strong) UITableView *tableView;//
-(void)reloadData;

@end
@implementation zhWallViewCell

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
-(instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier{
    
    if (self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]) {
        [self setupUI];
    }
    return self;
}
-(void)reloadData{
    [self.tableView reloadData];
}
-(void)setupUI{
    
    self.tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.tableView registerClass:[LSZDownloadCell class] forCellReuseIdentifier:LISTCELL];
    [self addSubview:self.tableView];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        if (@available(iOS 10, *)) {
            // iOS 10 及其以上系统运行
            make.edges.equalTo(self);
        }else{
            make.top.offset(50);
            make.left.offset(0);
            make.right.offset(0);
            make.bottom.equalTo(self);
        }
    }];
    
    // 2. 安装播放歌曲发生变化的通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(musicPlayerPlayingSongDidChangedNotification:) name:LCMusicPlayerPlayingSongDidChangedNotification object:_LCPlayer];
    
}
- (void)musicPlayerPlayingSongDidChangedNotification:(NSNotification *)notification {
    [self.tableView reloadData];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _LCPlayer.songs.count;
}
//高度
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 50;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    

    LSZDownloadCell *cell = [tableView dequeueReusableCellWithIdentifier:LISTCELL forIndexPath:indexPath];
    if (cell == nil) {
        cell = [[LSZDownloadCell alloc] initWithStyle:UITableViewCellStyleValue2 reuseIdentifier:LISTCELL];
    }

    cell.selectionStyle = UITableViewCellSelectionStyleNone;//未选中颜色
    JKSongsMessStatus *song = _LCPlayer.songs[indexPath.row];
    NSString *strText = [NSString stringWithFormat:@"%@ - %@",song.title,song.singerName];
    cell.textLabel.text = strText;

    cell.textLabel.font = [UIFont systemFontOfSize:15];
    UIButton *buttonTime = [[UIButton alloc] init];
    [buttonTime setTitleColor:[UIColor lightGrayColor] forState:0];
    if ([_LCPlayer.playingSong.singerName isEqualToString:@"圣经新约"] || [_LCPlayer.playingSong.singerName isEqualToString:@"圣经旧约"]) {
        if ([[LCHistoryDataManager loadBibleTextTitleData] isEqualToString:song.title]) {
            cell.textLabel.textColor = [UIColor redColor];
        }else{
            cell.textLabel.textColor = [UIColor blackColor];
        }
    }else{
        if ([[LCHistoryDataManager loadOneSongsData] isEqualToString:song.title] && [song.fileUrl isEqualToString:_LCPlayer.playingSong.fileUrl]) {
            cell.textLabel.textColor = [UIColor redColor];
        }else{
            cell.textLabel.textColor = [UIColor blackColor];
        }
    }
    
    [buttonTime setTitle:[NSString stringWithFormat:@"%@",[LSZSpecialPackaging TimeStamp:song.duration]] forState:0];
    
    [buttonTime sizeToFit];
    buttonTime.titleLabel.font = [UIFont systemFontOfSize:15];
    buttonTime.tag = indexPath.row;
    [buttonTime addTarget:self action:@selector(deleSong:) forControlEvents:UIControlEventTouchUpInside];
    if (self.isPlayerVC) {
        cell.accessoryView = buttonTime;
        cell.butDeleting.alpha = 0;
    }else{
        cell.butDeleting.tag = indexPath.row;
        [cell.butDeleting addTarget:self action:@selector(deleSong:) forControlEvents:UIControlEventTouchUpInside];
    }
    
    return cell;
}
-(void)deleSong:(UIButton *)sender{
    if (_LCPlayer.songs.count == 1) {
        [_LCPlayer stop];
    }
    NSLog(@"删除第 = %zd行", sender.tag);
    
    NSMutableArray *mutableArray = [[NSMutableArray alloc] init];
    mutableArray = [_LCPlayer.songs mutableCopy];
    [mutableArray removeObjectAtIndex:sender.tag];
    _LCPlayer.songs = [mutableArray copy];
    [self.tableView reloadData];
    
    if (_LCPlayer.selectedIndex > sender.tag) {
        _LCPlayer.selectedIndex -= 1;
    }
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [_LCPlayer playAtIndex:indexPath.row isSelectPlay:YES];
    [self.tableView reloadData];
}

@end

@implementation zhWallItemModel

+ (instancetype)modelWithImage:(UIImage *)image text:(NSString *)text {
    zhWallItemModel *model = [[zhWallItemModel alloc] init];
    model.image = image;
    model.text = text;
    return model;
}

@end

////////////////////////
// MARK -zhWallView - //
////////////////////////

@interface zhWallView () <UITableViewDataSource, UITableViewDelegate>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) zhWallViewCell *cell;
@property (nonatomic, strong) UIButton *songsButton;

@end

@implementation zhWallView

- (instancetype)init  {
    return [self initWithFrame:CGRectZero];
}

- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        self.backgroundColor = [UIColor colorWithRed:240 / 255. green:240 / 255. blue:240 / 255. alpha:0xff / 255.];
        


        _tableView = [[UITableView alloc] initWithFrame:self.bounds style:UITableViewStylePlain];
                //注册tableView
        [_tableView registerClass:[zhWallViewCell class] forCellReuseIdentifier:@"zh_wallViewCell"];

        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.bounces = NO;
        _tableView.delaysContentTouches = NO;
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.backgroundColor = [UIColor clearColor];
        [self addSubview:_tableView];
        
        _wallHeaderLabel = [self labelWithTextColor:[UIColor darkGrayColor] font:[UIFont systemFontOfSize:18] action:@selector(headerClicked)];
        
        UIView *view = [[UIView alloc] init];

        UIImageView *randomOrSingleImageView = [[UIImageView alloc] init];
        if (_LCPlayer.listStatus == LCMusicListStatusAllCycle) {
            randomOrSingleImageView.image = [[UIImage imageNamed:@"new循环"] imageWithTintColor:[UIColor lightGrayColor]];
        } else if(_LCPlayer.listStatus == LCMusicListStatusRandom){
            randomOrSingleImageView.image = [[UIImage imageNamed:@"new随机"] imageWithTintColor:[UIColor lightGrayColor]];
        }else if(_LCPlayer.listStatus == LCMusicListStatusSingleCycle){
            randomOrSingleImageView.image = [[UIImage imageNamed:@"new单曲"] imageWithTintColor:[UIColor lightGrayColor]];
        }
        [view addSubview:randomOrSingleImageView];
        
        [_wallHeaderLabel sizeToFit];
        [view addSubview:_wallHeaderLabel];
        UIButton *songsButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 50, 30)];
        _songsButton = songsButton;
        [songsButton setTitleColor:[UIColor blackColor] forState:0];
        [songsButton setTitle:[NSString stringWithFormat:@"%@(%zd首)",[self randomOrSinglePlayStr],_LCPlayer.songs.count] forState:0];
        
        [view addSubview:songsButton];
        _tableView.tableHeaderView = view;

        _wallFooterLabel = [self labelWithTextColor:[UIColor blackColor] font:[UIFont systemFontOfSize:18] action:@selector(footerClicked)];
        _wallFooterLabel.backgroundColor = [UIColor whiteColor];
        _tableView.tableFooterView = _wallFooterLabel;
        //循环图标
        [randomOrSingleImageView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.equalTo(_tableView.tableHeaderView.mas_centerY);
            make.left.offset(18);
        }];
        //循环多少首
        [songsButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.equalTo(_tableView.tableHeaderView.mas_centerY);
            make.left.equalTo(randomOrSingleImageView.mas_right).offset(20);
        }];
        //清空
        [_wallHeaderLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.equalTo(_tableView.tableHeaderView.mas_centerY);
            make.right.offset(-16);
        }];
    }
    return self;
}
- (NSString *)randomOrSinglePlayStr{
    NSString *str;
    if (_LCPlayer.listStatus == LCMusicListStatusAllCycle) {
        str = @"循环播放";
    } else if(_LCPlayer.listStatus == LCMusicListStatusRandom){
        str = @"随机播放";
    }else if(_LCPlayer.listStatus == LCMusicListStatusSingleCycle){
        str = @"单曲播放";
    }
    return str;
}


- (UILabel *)labelWithTextColor:(UIColor *)textColor font:(UIFont *)font action:(nullable SEL)action {
    UILabel *label = [[UILabel alloc] init];
    label.textAlignment = NSTextAlignmentCenter;
    label.userInteractionEnabled = YES;
    label.text = @"zhWallView";
    label.textColor = textColor;
    label.font = font;
    [label addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:action]];
    return label;
}

#pragma mark - UITableViewDataSource, UITableViewDelegate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (@available(iOS 10, *)) {
        // iOS 10 及其以上系统运行
        return [self wallSectionHeight] * 3 - 20 - 20;
    }else{
        return [self wallSectionHeight] * 3 - 20 - 20 + 50;
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    zhWallViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"zh_wallViewCell" forIndexPath:indexPath];
    _cell = cell;
    cell.isPlayerVC = _isPlayerVC;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;//未选中颜色
    return cell;
}

#pragma mark - Gesture block
//清空处理
- (void)headerClicked {
    [_songsButton setTitle:[NSString stringWithFormat:@"%@(0首)",[self randomOrSinglePlayStr]] forState:0];
    [_PlaylistMgr removeAllPlaylists];
    LCPlaylist *playlistTest = _PlaylistMgr.allPlaylists.firstObject;
    _LCPlayer.songs = playlistTest.allSongs;
    _LCPlayer.playingShengJing = -1;
    [_cell reloadData];
    if (self.didClickHeader) self.didClickHeader(self);
}

- (void)footerClicked {
    if (nil != self.didClickFooter) self.didClickFooter(self);
}

#pragma mark - <zhSheetViewConfigDelegate>

- (zhWallViewLayout *)layout {
    id <zhWallViewDelegateConfig> config = (id <zhWallViewDelegateConfig> )self.delegate;
    if ([config respondsToSelector:@selector(layoutOfItemInWallView:)]) {
        return [config layoutOfItemInWallView:self];
    }
    return [[zhWallViewLayout alloc] init];
}

- (zhWallViewAppearance *)appearance {
    id <zhWallViewDelegateConfig> config = (id <zhWallViewDelegateConfig> )self.delegate;
    if ([config respondsToSelector:@selector(appearanceOfItemInWallView:)]) {
        return [config appearanceOfItemInWallView:self];
    }
    return [[zhWallViewAppearance alloc] init];
}

#pragma mark - Setter

- (void)setModels:(NSArray<NSArray<zhWallItemModel *> *> *)models {
    _models = models;
    [self reloadTableViewHeaderAndFooterHeight];
    [_tableView reloadData];
}

- (void)reloadTableViewHeaderAndFooterHeight {
//    NSLog(@"self.layout.wallHeaderHeight = %f", self.layout.wallHeaderHeight);//30
    _tableView.tableHeaderView.size = CGSizeMake(self.width, 50);//self.layout.wallHeaderHeight);
    _tableView.tableFooterView.size = CGSizeMake(self.width, self.layout.wallFooterHeight+20);
}

#pragma mark - Wall section height

- (CGFloat)wallSectionHeight {
    return self.layout.itemEdgeInset.top + self.layout.itemEdgeInset.bottom + self.layout.itemSize.height;
}

- (void)autoAdjustFitHeight {
    CGFloat totalHeight = [self wallSectionHeight] * 3;
    if (!CGRectEqualToRect(CGRectZero, _wallHeaderLabel.frame)) {
        totalHeight += self.layout.wallHeaderHeight;
    }
    if (!CGRectEqualToRect(CGRectZero, _wallFooterLabel.frame)) {
        totalHeight += self.layout.wallFooterHeight;
    }
    self.height = _tableView.height = totalHeight;
}

@end
